<?php

namespace App\Services\Third;

use App\Events\AdminLogEvent;
use App\Http\Request;
use App\Models\AdminLog;
use Illuminate\Support\Facades\Route;

class AdminLogDb
{

    /**
     * @var AdminLog
     */
    private $model;

    /**
     * @param \Illuminate\Http\Request $request
     * @return $this
     */
    public function apiStart($request)
    {
        $this->model = new AdminLog();
        $params      = $this->model->asJson($request->all());
        $this->model->name       = Route::currentRouteName();
        $this->model->ip_address = $request->getClientIp();
        $this->model->params     = strlen($params) > 10000 ? '' : $params;
        $this->model->uri        = $request->getPathInfo();
        $this->model->method     = $request->method();
        $this->model->start_time = get_m_sec_time();
        return $this;
    }

    /**
     * @param \Illuminate\Http\Response $response
     * @return bool
     */
    public function apiFinish($response)
    {
        if ($this->model->uri === '/api/admin/check') return true;
        $responseContent = json_decode($response->getContent(), true);
        /** @var AdminLog $model */
        $model = $this->model;
        if (mb_strlen($response->getContent(), 'utf-8') > 99999) {
            $responseContent = [
                'code'    => $response->getStatusCode(),
                'message' => isset($responseContent['message']) ? $responseContent['message'] : '',
                'data'    => new \ArrayObject()
            ];
        }
        $model->end_time    = get_m_sec_time();
        $model->con_time    = $model->end_time - $model->start_time;
        $model->res_code    = $responseContent['code'] ?? $response->getStatusCode();
        $model->res_msg     = isset($responseContent['message']) ? $model->asJson($responseContent['message']) : '';
        $model->res_content = $model->asJson($responseContent);
        $model->admin_id    = admin(false)->adminId();
        AdminLogEvent::dispatch($model->getAttributes());
        return true;
    }
}
